﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Data.Common;
using System.Data.SqlClient;

namespace DatabaseModule
{
    //Specific module for Microsoft SQL Server
    class dbMSSQL : SQLDatabase
    {
        //Constructor
        public dbMSSQL(string connStr)
        {
            //Read in the connection string and store it for later use
            connectionString = connStr;

            //No errors have ocurred yet
            errorStr = "";

            //Not in verbose mode by default
            SetVerboseMode(false);
        }

        //Create a new connection for each function call
        protected override DbConnection createConnection()
        {
            try
            {
                //Create a new connection using our stored connection string
                DbConnection conn = new SqlConnection(connectionString);

                //Open the connection
                conn.Open();

                //Return the handle
                return conn;
            }
            catch (Exception)
            {
                //Could not connect to the database
                return null;
            }
        }

        //Create an SQL command
        protected override DbCommand createCommand(string sql, DbConnection conn)
        {
            return new SqlCommand(sql, (SqlConnection)conn);
        }

        //Create an SQL parameter
        protected override void addParameter(ref DbCommand cmd, string name, object value)
        {
            SqlCommand mCmd = (SqlCommand)cmd;
            mCmd.Parameters.AddWithValue(name, value);
        }

        //Uses implementation-specific limiting functionality
        protected override string applyLimit(string sql, int limit)
        {
            if (limit > 0)
            {
                //Use the LIMIT syntax
                return sql.Replace("SELECT ", "SELECT TOP " + limit + " ");
            }
            else
            {
                return sql;
            }
        }
    }
}
